package com.sbw.tinysoft.controller;

import com.alibaba.fastjson.JSON;
import com.sbw.tinysoft.core.entity.Article;
import com.sbw.tinysoft.core.entity.VisaApi2Services;
import com.sbw.tinysoft.core.service.ArticleService;
import com.sbw.tinysoft.core.service.VisaService2ProjectsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisKeyValueTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 默认页面
 * Created by sbw on 2017/3/11.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private VisaService2ProjectsService visaService2ProjectsService;

    @ResponseBody
    @GetMapping("/get/stage/{stage}")
    public List<Article> getArticleByStage(@PathVariable("stage") Integer stage) throws Exception {
        return articleService.forWeekly(stage);
    }

    @RequestMapping("/get/stage/html")
    public String getArticleByStage(Integer stage, ModelMap model) throws Exception {
//        List<Article> articles = articleService.forWeekly(stage);
//        model.addAttribute("articles",articles);
        return "index";
    }

    /**
     * 获取 签证对外服务调用工程
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/get/visaApi/projects")
    @ResponseBody
    public Object getVisaApiProjects(ModelMap model) throws Exception {
        parseTxt();
        VisaApi2Services visaApi2Services = visaService2ProjectsService.parseVisaApiProjectsRelation();
        System.out.printf("json string is "+ JSON.toJSONString(visaApi2Services));
        return JSON.toJSON(visaApi2Services);
    }

    @RequestMapping("/init/ip/projects")
    public String initIpProjects(ModelMap model) throws Exception {
        parseTxt();
        return "index";
    }

    private void init(){
        Set<String> set1=new HashSet<String>();
        set1.add("set1");
        set1.add("set2");
        set1.add("set3");
        redisTemplate.opsForSet().add("set1",set1);
        Set<String> resultSet =redisTemplate.opsForSet().members("set1");
        System.out.println("resultSet:"+resultSet);


        Map<String,String> map=new HashMap<String,String>();
        map.put("key1","value1");
        map.put("key2","value2");
        map.put("key3","value3");
        map.put("key4","value4");
        map.put("key5","value5");
        redisTemplate.opsForHash().putAll("map1",map);
        Map<String,String> resultMap= redisTemplate.opsForHash().entries("map1");
        List<String>reslutMapList=redisTemplate.opsForHash().values("map1");
        Set<String>resultMapSet=redisTemplate.opsForHash().keys("map1");
        String value=(String)redisTemplate.opsForHash().get("map1","key1");
        System.out.println("value:"+value);
        System.out.println("resultMapSet:"+resultMapSet);
        System.out.println("resultMap:"+resultMap);
        System.out.println("resulreslutMapListtMap:"+reslutMapList);

        List<String> list1=new ArrayList<String>();
        list1.add("a1");
        list1.add("a2");
        list1.add("a3");

        List<String> list2=new ArrayList<String>();
        list2.add("b1");
        list2.add("b2");
        list2.add("b3");
        redisTemplate.opsForList().leftPush("listkey1",list1);
        redisTemplate.opsForList().rightPush("listkey2",list2);
        redisTemplate.opsForValue().set("list_object",list2);
        List<String> resultList1=(List<String>)redisTemplate.opsForList().leftPop("listkey1");
        List<String> resultList2=(List<String>)redisTemplate.opsForList().rightPop("listkey2");
        List<String> resultList3=(List<String>)redisTemplate.opsForValue().get("list_object");
        System.out.println("resultList1:"+resultList1);
        System.out.println("resultList2:"+resultList2);
        System.out.println("resultList2:"+resultList3);
    }

    private void parseTxt(){
        try {
            File file = ResourceUtils.getFile("classpath:doc/visa_ips.txt");
            InputStreamReader reader = new InputStreamReader( new FileInputStream(file)); // 建立一个输入流对象reader
            BufferedReader br = new BufferedReader(reader); 	// 建立一个对象，它把文件内容转成计算机能读懂的语言
            Map<String,List<String>> ipProjectsMap = new HashMap<>();
            String lineTxt = null;
            while ((lineTxt = br.readLine())!= null) {
                if(!StringUtils.isEmpty(lineTxt)){
                    lineTxt = lineTxt.trim(); // 一次读入一行数据
                    handleIpProjectsRelation(lineTxt,ipProjectsMap);
                }
            }
            br.close();
            reader.close();
            System.out.println("关闭输入流");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void handleIpProjectsRelation(String lineText,Map<String,List<String>> ipProjectsMap){
        if(StringUtils.isEmpty(lineText)){
            return;
        }

        if(null==ipProjectsMap){
            ipProjectsMap = new HashMap<>();
        }

        String lineData = lineText.replace(" ","").replace("\t","");
        String lineReplace = lineData.replace("][",",");
        int index_1 = lineReplace.indexOf("[");
        if(index_1<0){
            return;
        }
        String project = lineReplace.substring(0,index_1);
        String line_ips_str = lineReplace.substring(index_1+1,lineReplace.length()-1);
        String[] line_ips = line_ips_str.split(",");
        for(String ip:line_ips){
            List<String> ipProjects = ipProjectsMap.get(ip);
            if(CollectionUtils.isEmpty(ipProjects)){
                ipProjects = new ArrayList<>();
            }
            if(!ipProjects.contains(project)){
                ipProjects.add(project);
                ipProjectsMap.put(ip,ipProjects);
            }
        }

        for (Map.Entry<String, List<String>> entry : ipProjectsMap.entrySet()) {
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            redisTemplate.opsForValue().set(entry.getKey(),entry.getValue());
        }
    }

}